package com.dsr.websocket;


import cn.hutool.core.date.DateTime;
import com.dsr.dao.MessageDao;
import com.dsr.entity.Message;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class MyHandler extends TextWebSocketHandler {

    private static Map<String, WebSocketSession> userMap = new HashMap<>();
    private static Map<String, WebSocketSession> adminMap = new HashMap<>();
    @Autowired
    private MessageDao messageDao;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage textMessage) throws Exception {
        String rawPath = session.getUri().getRawPath();
        String payload = textMessage.getPayload();
        ObjectMapper objectMapper = new ObjectMapper();
        Message message = objectMapper.readValue(payload, Message.class);
        if(StringUtils.isNotEmpty(message.getMessage())){
            if (rawPath.contains("user") ){
                for (String id:adminMap.keySet()){
                    adminMap.get(id).sendMessage(textMessage);
                }
            }else {
                String toUserId = message.getToUserId();
                if(userMap.containsKey(toUserId)){
                    userMap.get(toUserId).sendMessage(new TextMessage(objectMapper.writeValueAsString(message)));
                }else {
                    message.setCreateDate(DateTime.now());
                    messageDao.insert(message);
                }

            }
        }
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws IOException, InterruptedException {
        String rawPath = session.getUri().getRawPath();
        if (rawPath.contains("user")) {
            String id = rawPath.substring(rawPath.lastIndexOf("/") + 1);
            userMap.put(id, session);
        } else {
            adminMap.put(session.getId(), session);
        }

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String rawPath = session.getUri().getRawPath();
        if (rawPath.contains("user")) {
            String id = rawPath.substring(rawPath.lastIndexOf("/") + 1);
            userMap.remove(id);
        } else {
            adminMap.remove(session.getId());
        }
    }
}
